package tailflog

import (
	"encoding/json"
	"errors"
	"fmt"
	"golang.org/x/net/websocket"
	"html/template"
	"log"
	"net/http"
	"path"
	"runtime"
	"strings"
	"time"
)

const (
	PageIndex = "index.html"
	Page403   = "403.html"
)

//var ChanMsg = msg {
//	LogName: "错误日志",
//	Data: "Hello World!",
//}

// 开启 httpServer
func server(port int, seelog string) {

	defer func() {
		if err := recover(); err != nil {
			printError(errors.New("server panic"))
		}
	}()

	// socket链接
	http.Handle("/ws", websocket.Handler(genConn))

	// 访问页面
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		if !(strings.Replace(request.RequestURI, "/", "", -1) == seelog) {
			showPage(writer, Page403, nil)
			return
		}
		showPage(writer, PageIndex, slogs)
	})

	// 添加log日志
	http.HandleFunc("/add/seelog", func(writer http.ResponseWriter, request *http.Request) {
		adds := slog{}
		decoder := json.NewDecoder(request.Body)
		decoder.Decode(&adds)
		isExist := false
		for k, sl := range slogs {
			if sl.Name == adds.Name {
				slogs[k].Path = adds.Path
				isExist = true
			}
		}

		if adds.Path != "" && isExist == false {
			slogs = append(slogs, adds)
		}

		for _, slg := range slogs {
			println(slg.Name, slg.Path)
		}

		go Monitor()
	})

	http.HandleFunc("/get/seelog", func(writer http.ResponseWriter, request *http.Request) {
		b, _ := json.Marshal(slogs)
		writer.Write([]byte(b))
	})
	log.Println(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
}

// 输出page
func showPage(writer http.ResponseWriter, page string, data interface{}) {
	_, currentfile, _, _ := runtime.Caller(0) // 忽略错误
	filename := path.Join(path.Dir(currentfile), page)
	t, err := template.ParseFiles(filename)
	if err != nil {
		printError(err)
	}
	t.Execute(writer, data)
}

// 创建client对象
func genConn(ws *websocket.Conn) {
	c := &client{time.Now().String(), ws, make(chan msg, 1024), slogs[0].Name}
	Manager.register <- c
	go c.read()
	c.write()
}
